Micron Document




Interface (object-oriented programming)
part 5/6 · 9.9 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
In Rust, interfaces are called traits.cite-ref-5[4] In Rust, structs do not have methods, but instead implement traits which declare methods that the struct implements.

trait Pet {
fn speak(&self);
}
struct Dog<'a> {
name: &'a str
}
impl<'a> Dog<'a> {
fn new(name: &'a str) -> Self {
Dog { name }
}
}
impl Pet<'a> for Dog<'a> {
fn speak(&self) {
println!("{} says 'Woof!'", self.name);
}
}

See also

──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────